/**
 * Created by CFlower on 2017/11/9.
 */

// div映射数组
var reflect_table = new Array(
    {type:'DCH',num:'SDT'},{type:'FBG',num:'SFT'},{type:'CCD',num:'SCD'},
    {type:'ENV',num:'SET'},{type:'CNC',num:'SCN'});
// 所有的数据类型的个数
var tab_num_all = 5;

$(function () {
    // 变色特效
    var backgroundElement = window.top.cfgetTopBackgroundElement();
    $(backgroundElement).css("background","rgba(225,115,95,0.85)");

    $('#equipmentId').combobox({									        // 设备组合框
        url: 'equipment/getAllEquip',
        valueField: 'value',                                            // 值为设备id
        textField: 'text',                                              // 内容为设备名
        panelHeight: 'auto',
        editable: false,
        onChange: function (newValue, oldValue) {					    // 组合框变化响应函数
            $("#machiningId").combobox('clear');						// 清空工况输入框
            $("#machiningDate").combobox('clear');				    // 清空日期输入框
            $("#machiningProcess").combobox('clear');					// 清空工作段输入框
            $("#patternName").combobox('clear');					    // 清空模式输入框
            $.ajax({													// 加载所有工况
                cache: false,
                url: "timeMachining/getMachiningByEquip",
                data: {equipmentId: newValue},
                type: "POST",
                dataType: "json",
                success: function (result) {
                    console.log(result);								// 将查询数据库的结果放到工况类型组合框
                    $("#machiningId").combobox("loadData", result);
                }
            });
            $.ajax({													// 加载所有模式
                cache: false,
                url: "pattern/getPatternByEquipment",
                data: {equipmentId: newValue},
                type: "POST",
                dataType: "json",
                success: function (result) {
                    console.log(result);								// 将查询数据库的结果放到模式类型组合框
                    $("#patternName").combobox("loadData", result);
                }
            });
        }
    });
    $('#machiningId').combobox({							        // 工况类型组合框
        url: '',
        valueField: 'value',                                       // 值为某种工况的id
        textField: 'text',                                          // 内容为某种工况的名字
        panelHeight: 'auto',
        editable: false,
        onChange: function (newValue, oldValue) {			        // 组合框变化响应函数
            var equipmentTempid = $('#equipmentId').combobox("getValues").toString();
            $("#machiningDate").combobox('clear');				// 清空日期
            $("#machiningProcess").combobox('clear');				// 清空加工段
            $.ajax({
                cache: false,
                url: "timeMachining/getDateByEquipMachine",			// 根据设备和工况类型来获取日期
                data: {equipmentId: equipmentTempid, machiningId: newValue},
                type: "POST",
                dataType: "json",
                success: function (result) {
                    console.log(result);					// 将通道信息加载到通道组合框
                    for (var i=0;i<result.length;i++)
                    {
                        result[i].text = formatOnlyDate(result[i].text);
                        result[i].num = formatOnlyDate(result[i].num);
                    }
                    $("#machiningDate").combobox("loadData", result);
                }
            });
        }
    });
    $('#machiningDate').combobox({							        // 加工日期组合框
        url: '',
        valueField: 'text',
        textField: 'text',
        panelHeight: 'auto',
        editable: false,
        onChange: function (newValue, oldValue) {			                // 组合框变化响应函数
            var equipmentTempid = $('#equipmentId').combobox("getValues").toString();
            var machineTempid = $('#machiningId').combobox("getValues").toString();
            $("#machiningProcess").combobox('clear');				        // 清空加工段
            $.ajax({
                cache: false,
                url: "timeMachining/getProcessByEquipMachDate",			// 根据设备和工况类型以及日期来获取加工时间
                data: {equipmentId: equipmentTempid, machiningId: machineTempid,machiningDate:newValue},
                type: "POST",
                dataType: "json",
                success: function (result) {
                    var temparr=result;
                    // temparr.unshift({text:"全选/反选",num:"全选/反选",value:"-1"});
                    $('#machiningProcess').combobox("loadData", temparr);
                }
            });
        }
    });
    $('#machiningProcess').combobox({								// 工况时间段组合框
        valueField: 'num',
        textField: 'text',
        panelHeight: 'auto',
        // multiple: true,
        multiple: false,
        editable: false,
        // onChange:function (newValue){
        //     var select = $('#machiningProcess');
        //     var valueField = select.combobox("options").valueField;
        //     if($.inArray("全选/反选", newValue)!=-1) {
        //         if (!newValue[valueField]) {
        //             var data = select.combobox("getData");
        //             var values = select.combobox("getValues");
        //             var selectVaues = [];
        //             if (data.length!= values.length) {
        //                 data.reduce(function (prev, current, index, array) {
        //                     selectVaues.push(current[valueField]);
        //                 }, selectVaues);
        //             } else {
        //                 selectVaues.push(newValue[valueField]);
        //             }
        //             selectVaues .splice(0,1);
        //             select.combobox('setValues', selectVaues);
        //         }
        //     }
        // }
    });
    $('#patternName').combobox({									        // 设备组合框
        url: '',
        valueField: 'num',                                              // 值为模式
        textField: 'text',                                              // 内容为模式名
        panelHeight: 'auto',
        editable: false,
        onChange: function (newValue, oldValue) {                       // newValue就为目标模式
            deleteAllMessage();
            // alert(newValue);
            var patternStr = $('#patternName').combobox('getValues').toString();
            var patternCutArray = patternStr.split('@');
            if(patternCutArray.length==0) return;
            for(var i=0;i<patternCutArray.length;i++){
                if(patternCutArray[i].length==0) break;
                var patternArray = patternCutArray[i].split(',');
                if(patternArray[0].indexOf('SDT')!=-1){
                    adjustNumToindex('SDT',i);
                }
                else if(patternArray[0].indexOf('SFT')!=-1){
                    adjustNumToindex('SFT',i);
                }
                else if(patternArray[0].indexOf('SCD')!=-1){
                    adjustNumToindex('SCD',i);
                }
                else if(patternArray[0].indexOf('SET')!=-1){
                    adjustNumToindex('SET',i);
                }
                else {
                    adjustNumToindex('SCN',i);
                }
                addArrayToTab(i+1,patternArray);
            }
        }
    });

    $("#dia-add").dialog({
        title:"添加数据",
        modal: true,
        width: 350,
        height: 200,
        closed: true,
        buttons : [{
            text : '添加',
            iconCls : 'icon-add',
            handler : function () {

                var dataType = $("#typeName").html().toString().split('：')[1];
                var channelArray = $("#channelId").combobox("getValues");
                var monitorArray = $("#monitorId").combobox("getValues");

                // 获取加载的所有设备
                var Temp_equipment = $('#equipmentId').combobox("getData");
                // 获取选中的设备编号
                var equipmentTempNum;
                for(var i=0;i<Temp_equipment.length;i++){
                    if($('#equipmentId').combobox("getText")==Temp_equipment[i].text){
                        equipmentTempNum = Temp_equipment[i].num;break;
                    }
                }
                if(equipmentTempNum==undefined) {alert("请先选择设备！");$("#dia-add").dialog('close');return;}
                var tab_id;
                for(var i=0;i<reflect_table.length;i++){
                    if(reflect_table[i].num==dataType) {
                        tab_id=i+1;break;
                    }
                }
                var oTab = document.getElementById('tab_00'+tab_id.toString());
                switch (dataType){
                    case "SDT":{
                        if(monitorArray.length==0 || channelArray.length==0) {$("#dia-add").dialog('close');return;}
                        for(var i=0;i<channelArray.length;i++)
                            for(var j=0;j<monitorArray.length;j++)
                            {
                                var textContent = equipmentTempNum+'-'+dataType+
                                    PreFixInterge(channelArray[i]-1,2).toString()+'-'+PreFixInterge(monitorArray[j]-1,2)
                                var rowNums = oTab.rows.length;
                                var rowObj = oTab.insertRow(rowNums); // 添加一行
                                rowObj.insertCell(0).innerHTML = oTab.rows.length-1;
                                rowObj.insertCell(1).innerHTML = textContent;
                                rowObj.insertCell(2).innerHTML = '<a>上移</a>';
                                rowObj.insertCell(3).innerHTML = '<a>下移</a>';
                                rowObj.insertCell(4).innerHTML = '<a>删除</a>';
                                // 上移操作响应事件
                                rowObj.getElementsByTagName('a')[0].onclick = function () {
                                    var tempIdx = this.parentNode.parentNode.rowIndex;
                                    if(tempIdx==1) {alert("已到顶端！");return;}
                                    var tempData = oTab.rows[tempIdx].cells[1].innerHTML.toString();
                                    oTab.rows[tempIdx].cells[1].innerHTML=oTab.rows[tempIdx-1].cells[1].innerHTML.toString();
                                    oTab.rows[tempIdx-1].cells[1].innerHTML=tempData;
                                }
                                // 下移操作响应事件
                                rowObj.getElementsByTagName('a')[1].onclick = function () {
                                    var tempIdx = this.parentNode.parentNode.rowIndex;
                                    if(tempIdx==(oTab.rows.length-1)) {alert("已到底部！");return;}
                                    var tempData = oTab.rows[tempIdx].cells[1].innerHTML.toString();
                                    oTab.rows[tempIdx].cells[1].innerHTML=oTab.rows[tempIdx+1].cells[1].innerHTML.toString();
                                    oTab.rows[tempIdx+1].cells[1].innerHTML=tempData;
                                }
                                // 删除操作响应事件
                                rowObj.getElementsByTagName('a')[2].onclick = function () {
                                    oTab.deleteRow(this.parentNode.parentNode.rowIndex);
                                    // 序号重新编号
                                    for(var i=1;i<oTab.rows.length;i++){oTab.rows[i].cells[0].innerHTML=i;}
                                }
                            }
                        $("#dia-add").dialog('close');
                        break;
                    }
                    case "SFT":{
                        if(monitorArray.length==0 || channelArray.length==0) {$("#dia-add").dialog('close');return;}
                        for(var i=0;i<channelArray.length;i++)
                            for(var j=0;j<monitorArray.length;j++)
                            {
                                var textContent = equipmentTempNum+'-'+dataType+
                                    PreFixInterge(channelArray[i]-1,2).toString()+'-'+PreFixInterge(monitorArray[j]-1,2)
                                var rowNums = oTab.rows.length;
                                var rowObj = oTab.insertRow(rowNums); // 添加一行
                                rowObj.insertCell(0).innerHTML = oTab.rows.length-1;
                                rowObj.insertCell(1).innerHTML = textContent;
                                rowObj.insertCell(2).innerHTML = '<a>上移</a>';
                                rowObj.insertCell(3).innerHTML = '<a>下移</a>';
                                rowObj.insertCell(4).innerHTML = '<a>删除</a>';
                                // 上移操作响应事件
                                rowObj.getElementsByTagName('a')[0].onclick = function () {
                                    var tempIdx = this.parentNode.parentNode.rowIndex;
                                    if(tempIdx==1) {alert("已到顶端！");return;}
                                    var tempData = oTab.rows[tempIdx].cells[1].innerHTML.toString();
                                    oTab.rows[tempIdx].cells[1].innerHTML=oTab.rows[tempIdx-1].cells[1].innerHTML.toString();
                                    oTab.rows[tempIdx-1].cells[1].innerHTML=tempData;
                                }
                                // 下移操作响应事件
                                rowObj.getElementsByTagName('a')[1].onclick = function () {
                                    var tempIdx = this.parentNode.parentNode.rowIndex;
                                    if(tempIdx==(oTab.rows.length-1)) {alert("已到底部！");return;}
                                    var tempData = oTab.rows[tempIdx].cells[1].innerHTML.toString();
                                    oTab.rows[tempIdx].cells[1].innerHTML=oTab.rows[tempIdx+1].cells[1].innerHTML.toString();
                                    oTab.rows[tempIdx+1].cells[1].innerHTML=tempData;
                                }
                                // 删除操作响应事件
                                rowObj.getElementsByTagName('a')[2].onclick = function () {
                                    oTab.deleteRow(this.parentNode.parentNode.rowIndex);
                                    // 序号重新编号
                                    for(var i=1;i<oTab.rows.length;i++){oTab.rows[i].cells[0].innerHTML=i;}
                                }
                            }
                        $("#dia-add").dialog('close');
                        break;
                    }
                    case "SCD":{
                        if(monitorArray.length==0) {$("#dia-add").dialog('close');return;}
                        for(var j=0;j<monitorArray.length;j++)
                        {
                            var textContent = equipmentTempNum+'-'+dataType+'-'+PreFixInterge(monitorArray[j]-1,2)
                            var rowNums = oTab.rows.length;
                            var rowObj = oTab.insertRow(rowNums); // 添加一行
                            rowObj.insertCell(0).innerHTML = oTab.rows.length-1;
                            rowObj.insertCell(1).innerHTML = textContent;
                            rowObj.insertCell(2).innerHTML = '<a>上移</a>';
                            rowObj.insertCell(3).innerHTML = '<a>下移</a>';
                            rowObj.insertCell(4).innerHTML = '<a>删除</a>';
                            // 上移操作响应事件
                            rowObj.getElementsByTagName('a')[0].onclick = function () {
                                var tempIdx = this.parentNode.parentNode.rowIndex;
                                if(tempIdx==1) {alert("已到顶端！");return;}
                                var tempData = oTab.rows[tempIdx].cells[1].innerHTML.toString();
                                oTab.rows[tempIdx].cells[1].innerHTML=oTab.rows[tempIdx-1].cells[1].innerHTML.toString();
                                oTab.rows[tempIdx-1].cells[1].innerHTML=tempData;
                            }
                            // 下移操作响应事件
                            rowObj.getElementsByTagName('a')[1].onclick = function () {
                                var tempIdx = this.parentNode.parentNode.rowIndex;
                                if(tempIdx==(oTab.rows.length-1)) {alert("已到底部！");return;}
                                var tempData = oTab.rows[tempIdx].cells[1].innerHTML.toString();
                                oTab.rows[tempIdx].cells[1].innerHTML=oTab.rows[tempIdx+1].cells[1].innerHTML.toString();
                                oTab.rows[tempIdx+1].cells[1].innerHTML=tempData;
                            }
                            // 删除操作响应事件
                            rowObj.getElementsByTagName('a')[2].onclick = function () {
                                oTab.deleteRow(this.parentNode.parentNode.rowIndex);
                                // 序号重新编号
                                for(var i=1;i<oTab.rows.length;i++){oTab.rows[i].cells[0].innerHTML=i;}
                            }
                        }
                        $("#dia-add").dialog('close');
                        break;
                    }
                    case "SET":{
                        if(monitorArray.length==0 || channelArray.length==0) {$("#dia-add").dialog('close');return;}
                        for(var i=0;i<channelArray.length;i++)
                            for(var j=0;j<monitorArray.length;j++)
                            {
                                var textContent = equipmentTempNum+'-'+dataType+
                                    PreFixInterge(channelArray[i]-1,2).toString()+'-'+PreFixInterge(monitorArray[j]-1,2)
                                var rowNums = oTab.rows.length;
                                var rowObj = oTab.insertRow(rowNums); // 添加一行
                                rowObj.insertCell(0).innerHTML = oTab.rows.length-1;
                                rowObj.insertCell(1).innerHTML = textContent;
                                rowObj.insertCell(2).innerHTML = '<a>上移</a>';
                                rowObj.insertCell(3).innerHTML = '<a>下移</a>';
                                rowObj.insertCell(4).innerHTML = '<a>删除</a>';
                                // 上移操作响应事件
                                rowObj.getElementsByTagName('a')[0].onclick = function () {
                                    var tempIdx = this.parentNode.parentNode.rowIndex;
                                    if(tempIdx==1) {alert("已到顶端！");return;}
                                    var tempData = oTab.rows[tempIdx].cells[1].innerHTML.toString();
                                    oTab.rows[tempIdx].cells[1].innerHTML=oTab.rows[tempIdx-1].cells[1].innerHTML.toString();
                                    oTab.rows[tempIdx-1].cells[1].innerHTML=tempData;
                                }
                                // 下移操作响应事件
                                rowObj.getElementsByTagName('a')[1].onclick = function () {
                                    var tempIdx = this.parentNode.parentNode.rowIndex;
                                    if(tempIdx==(oTab.rows.length-1)) {alert("已到底部！");return;}
                                    var tempData = oTab.rows[tempIdx].cells[1].innerHTML.toString();
                                    oTab.rows[tempIdx].cells[1].innerHTML=oTab.rows[tempIdx+1].cells[1].innerHTML.toString();
                                    oTab.rows[tempIdx+1].cells[1].innerHTML=tempData;
                                }
                                // 删除操作响应事件
                                rowObj.getElementsByTagName('a')[2].onclick = function () {
                                    oTab.deleteRow(this.parentNode.parentNode.rowIndex);
                                    // 序号重新编号
                                    for(var i=1;i<oTab.rows.length;i++){oTab.rows[i].cells[0].innerHTML=i;}
                                }
                            }
                        $("#dia-add").dialog('close');
                        break;
                    }
                    case "SCN":{
                        if(monitorArray.length==0) {$("#dia-add").dialog('close');return;}
                        for(var j=0;j<monitorArray.length;j++)
                        {
                            var textContent = equipmentTempNum+'-'+dataType+ '-'+monitorArray[j];
                            var rowNums = oTab.rows.length;
                            var rowObj = oTab.insertRow(rowNums); // 添加一行
                            rowObj.insertCell(0).innerHTML = oTab.rows.length-1;
                            rowObj.insertCell(1).innerHTML = textContent;
                            rowObj.insertCell(2).innerHTML = '<a>上移</a>';
                            rowObj.insertCell(3).innerHTML = '<a>下移</a>';
                            rowObj.insertCell(4).innerHTML = '<a>删除</a>';
                            // 上移操作响应事件
                            rowObj.getElementsByTagName('a')[0].onclick = function () {
                                var tempIdx = this.parentNode.parentNode.rowIndex;
                                if(tempIdx==1) {alert("已到顶端！");return;}
                                var tempData = oTab.rows[tempIdx].cells[1].innerHTML.toString();
                                oTab.rows[tempIdx].cells[1].innerHTML=oTab.rows[tempIdx-1].cells[1].innerHTML.toString();
                                oTab.rows[tempIdx-1].cells[1].innerHTML=tempData;
                            }
                            // 下移操作响应事件
                            rowObj.getElementsByTagName('a')[1].onclick = function () {
                                var tempIdx = this.parentNode.parentNode.rowIndex;
                                if(tempIdx==(oTab.rows.length-1)) {alert("已到底部！");return;}
                                var tempData = oTab.rows[tempIdx].cells[1].innerHTML.toString();
                                oTab.rows[tempIdx].cells[1].innerHTML=oTab.rows[tempIdx+1].cells[1].innerHTML.toString();
                                oTab.rows[tempIdx+1].cells[1].innerHTML=tempData;
                            }
                            // 删除操作响应事件
                            rowObj.getElementsByTagName('a')[2].onclick = function () {
                                oTab.deleteRow(this.parentNode.parentNode.rowIndex);
                                // 序号重新编号
                                for(var i=1;i<oTab.rows.length;i++){oTab.rows[i].cells[0].innerHTML=i;}
                            }
                        }
                        $("#dia-add").dialog('close');
                        break;
                    }
                    default:break;
                }
            }
        },{
            text : '取消',
            iconCls : 'icon-redo',
            handler : function () {
                $("#dia-add").dialog('close');
            }
        }]
    });

});

// 往数据库里录入自定义的模式
function addPatternToDatabase(){
    // 获取设备id
    var eqText = $('#equipmentId').combobox("getText");
    if(eqText=="") {alert("请选择设备！");return;}
    var equipmentTempid = $('#equipmentId').combobox("getValues").toString();

    // 下载目标字符串
    var stringArrayTemp=genAllDataString();
    if(stringArrayTemp=="") {alert("请添加传感器数据后再录入模式！");return;}

    // 获取模式名
    var patternNameStr = $("#patternNameSet").textbox('getText');
    if(patternNameStr=="") {alert("请填写自定义的模式名！");return;}

    // 请求序列
    var seqStr = 'equipmentId=' + equipmentTempid + '&' +
                  'patternName=' + patternNameStr + '&' +
                  'pattern='     + stringArrayTemp;
    // 调用后台请求添加数据
    $.ajax({
        cache:false,
        url:'pattern/add',
        data:seqStr,
        type:"POST",
        dataType:"json",
        success:function(result){
            if(!result.success){
                alert(result.msg);
            }else{
                alert(result.msg);
            }
        }
    });

}


// 保留字符宽度函数
function PreFixInterge(num,n){
    //num代表传入的数字，n代表要保留的字符的长度
    return (Array(n).join(0)+num).slice(-n);
}

// 添加数据的响应事件
function addMessage(type_num){
    // 获取id的名字
    var in_id = "type_00" + type_num.toString();
    // 获取数据类型名
    var stype = getTypeFromID(in_id);
    // 获取加载的所有设备
    var Temp_equipment = $('#equipmentId').combobox("getData");

    // 获取选中的设备编号
    var equipmentTempNum;
    for(var i=0;i<Temp_equipment.length;i++){
        if($('#equipmentId').combobox("getText")==Temp_equipment[i].text){
            equipmentTempNum = Temp_equipment[i].num;break;
        }
    }
    if(equipmentTempNum==undefined) {alert("请先选择设备！");return;}

    // 生成通道数组和节点数组
    var channelArray = new Array();
    var monitorArray = new Array();
    switch(stype)
    {
        case "DCH":
            channelArray = genChannelArray(7);
            monitorArray = genMonitorArray(8);
            initComboBoxML('#dia-add #channelId', channelArray);
            initComboBoxML('#dia-add #monitorId', monitorArray);
            $("#typeName").html("当前数据类型：SDT");
            $("#dia-add").dialog('open');
            break;
        case "FBG":
            channelArray = genChannelArray(32);
            monitorArray = genMonitorArray(20);
            initComboBoxML('#dia-add #channelId', channelArray);
            initComboBoxML('#dia-add #monitorId', monitorArray);
            $("#typeName").html("当前数据类型：SFT");
            $("#dia-add").dialog('open');
            break;
        case "CCD":
            initComboBoxCCD();
            $("#typeName").html("当前数据类型：SCD");
            $("#dia-add").dialog('open');
            break;
        case "ENV":
            channelArray = genChannelArray(2);
            monitorArray = genMonitorArray(2);
            initComboBoxML('#dia-add #channelId', channelArray);
            initComboBoxML('#dia-add #monitorId', monitorArray);
            $("#typeName").html("当前数据类型：SET");
            $("#dia-add").dialog('open');
            break;
        case "CNC":
            initComboBoxCNC();
            $("#typeName").html("当前数据类型：SCN");
            $("#dia-add").dialog('open');
            break;
        default : break;
    }

};

// 添加左移的响应事件
function leftMessage(type_num){
    if(type_num==1) {return;}
    var tempArr = reflect_table[type_num-1];
    reflect_table[type_num-1]=reflect_table[type_num-2];
    reflect_table[type_num-2]=tempArr;

    // // 获取id的名字
    document.getElementById("type_00" + type_num.toString()).innerText=reflect_table[type_num-1].type;
    document.getElementById("type_00" + (type_num-1).toString()).innerText=reflect_table[type_num-2].type;

    // 将现在的表内容存储并清空
    var oTabNow = document.getElementById('tab_00'+ type_num.toString());
    var rowNumsNow = oTabNow.rows.length;
    var textArrayTemp=new Array();
    for(var i=1;i<rowNumsNow;i++) {
        textArrayTemp.push(oTabNow.rows[1].cells[1].innerHTML.toString());
        oTabNow.rows[1].getElementsByTagName('a')[2].onclick();
    }
    // 将前一个表的内容移到现在的表
    var oTabBefore = document.getElementById('tab_00'+ (type_num-1).toString());
    var rowNumsBefore = oTabBefore.rows.length;
    for(var i=1;i<rowNumsBefore;i++) {
        var rowObj = oTabNow.insertRow(oTabNow.rows.length); // 添加一行
        rowObj.insertCell(0).innerHTML = oTabNow.rows.length-1;
        rowObj.insertCell(1).innerHTML = oTabBefore.rows[1].cells[1].innerHTML.toString();
        oTabBefore.rows[1].getElementsByTagName('a')[2].onclick();
        rowObj.insertCell(2).innerHTML = '<a>上移</a>';
        rowObj.insertCell(3).innerHTML = '<a>下移</a>';
        rowObj.insertCell(4).innerHTML = '<a>删除</a>';
        // 上移操作响应事件
        rowObj.getElementsByTagName('a')[0].onclick = function () {
            var tempIdx = this.parentNode.parentNode.rowIndex;
            if(tempIdx==1) {alert("已到顶端！");return;}
            var tempData = oTabNow.rows[tempIdx].cells[1].innerHTML.toString();
            oTabNow.rows[tempIdx].cells[1].innerHTML=oTabNow.rows[tempIdx-1].cells[1].innerHTML.toString();
            oTabNow.rows[tempIdx-1].cells[1].innerHTML=tempData;
        }
        // 下移操作响应事件
        rowObj.getElementsByTagName('a')[1].onclick = function () {
            var tempIdx = this.parentNode.parentNode.rowIndex;
            if(tempIdx==(oTabNow.rows.length-1)) {alert("已到底部！");return;}
            var tempData = oTabNow.rows[tempIdx].cells[1].innerHTML.toString();
            oTabNow.rows[tempIdx].cells[1].innerHTML=oTabNow.rows[tempIdx+1].cells[1].innerHTML.toString();
            oTabNow.rows[tempIdx+1].cells[1].innerHTML=tempData;
        }
        // 删除操作响应事件
        rowObj.getElementsByTagName('a')[2].onclick = function () {
            oTabNow.deleteRow(this.parentNode.parentNode.rowIndex);
            // 序号重新编号
            for(var i=1;i<oTabNow.rows.length;i++){oTabNow.rows[i].cells[0].innerHTML=i;}
        }
    }
    // 将存起来的内容复制到前一个表
    for(var i=1;i<rowNumsNow;i++){
        var rowObj = oTabBefore.insertRow(oTabBefore.rows.length); // 添加一行
        rowObj.insertCell(0).innerHTML = oTabBefore.rows.length-1;
        rowObj.insertCell(1).innerHTML = textArrayTemp[i-1];
        rowObj.insertCell(2).innerHTML = '<a>上移</a>';
        rowObj.insertCell(3).innerHTML = '<a>下移</a>';
        rowObj.insertCell(4).innerHTML = '<a>删除</a>';
        // 上移操作响应事件
        rowObj.getElementsByTagName('a')[0].onclick = function () {
            var tempIdx = this.parentNode.parentNode.rowIndex;
            if(tempIdx==1) {alert("已到顶端！");return;}
            var tempData = oTabBefore.rows[tempIdx].cells[1].innerHTML.toString();
            oTabBefore.rows[tempIdx].cells[1].innerHTML=oTabBefore.rows[tempIdx-1].cells[1].innerHTML.toString();
            oTabBefore.rows[tempIdx-1].cells[1].innerHTML=tempData;
        }
        // 下移操作响应事件
        rowObj.getElementsByTagName('a')[1].onclick = function () {
            var tempIdx = this.parentNode.parentNode.rowIndex;
            if(tempIdx==(oTabBefore.rows.length-1)) {alert("已到底部！");return;}
            var tempData = oTabBefore.rows[tempIdx].cells[1].innerHTML.toString();
            oTabBefore.rows[tempIdx].cells[1].innerHTML=oTabBefore.rows[tempIdx+1].cells[1].innerHTML.toString();
            oTabBefore.rows[tempIdx+1].cells[1].innerHTML=tempData;
        }
        // 删除操作响应事件
        rowObj.getElementsByTagName('a')[2].onclick = function () {
            oTabBefore.deleteRow(this.parentNode.parentNode.rowIndex);
            // 序号重新编号
            for(var i=1;i<oTabBefore.rows.length;i++){oTabBefore.rows[i].cells[0].innerHTML=i;}
        }

    }

};

// 添加右移的响应事件
function rightMessage(type_num){
    if(type_num==(tab_num_all-1)) {return;}
    var tempArr = reflect_table[type_num-1];
    reflect_table[type_num-1]=reflect_table[type_num];
    reflect_table[type_num]=tempArr;

    // // 获取id的名字
    document.getElementById("type_00" + type_num.toString()).innerText=reflect_table[type_num-1].type;
    document.getElementById("type_00" + (type_num+1).toString()).innerText=reflect_table[type_num].type;

    // 将现在的表内容存储并清空
    var oTabNow = document.getElementById('tab_00'+ type_num.toString());
    var rowNumsNow = oTabNow.rows.length;
    var textArrayTemp=new Array();
    for(var i=1;i<rowNumsNow;i++) {
        textArrayTemp.push(oTabNow.rows[1].cells[1].innerHTML.toString());
        oTabNow.rows[1].getElementsByTagName('a')[2].onclick();
    }
    // 将前一个表的内容移到现在的表
    var oTabBefore = document.getElementById('tab_00'+ (type_num+1).toString());
    var rowNumsBefore = oTabBefore.rows.length;
    for(var i=1;i<rowNumsBefore;i++) {
        var rowObj = oTabNow.insertRow(oTabNow.rows.length); // 添加一行
        rowObj.insertCell(0).innerHTML = oTabNow.rows.length-1;
        rowObj.insertCell(1).innerHTML = oTabBefore.rows[1].cells[1].innerHTML.toString();
        oTabBefore.rows[1].getElementsByTagName('a')[2].onclick();
        rowObj.insertCell(2).innerHTML = '<a>上移</a>';
        rowObj.insertCell(3).innerHTML = '<a>下移</a>';
        rowObj.insertCell(4).innerHTML = '<a>删除</a>';
        // 上移操作响应事件
        rowObj.getElementsByTagName('a')[0].onclick = function () {
            var tempIdx = this.parentNode.parentNode.rowIndex;
            if(tempIdx==1) {alert("已到顶端！");return;}
            var tempData = oTabNow.rows[tempIdx].cells[1].innerHTML.toString();
            oTabNow.rows[tempIdx].cells[1].innerHTML=oTabNow.rows[tempIdx-1].cells[1].innerHTML.toString();
            oTabNow.rows[tempIdx-1].cells[1].innerHTML=tempData;
        }
        // 下移操作响应事件
        rowObj.getElementsByTagName('a')[1].onclick = function () {
            var tempIdx = this.parentNode.parentNode.rowIndex;
            if(tempIdx==(oTabNow.rows.length-1)) {alert("已到底部！");return;}
            var tempData = oTabNow.rows[tempIdx].cells[1].innerHTML.toString();
            oTabNow.rows[tempIdx].cells[1].innerHTML=oTabNow.rows[tempIdx+1].cells[1].innerHTML.toString();
            oTabNow.rows[tempIdx+1].cells[1].innerHTML=tempData;
        }
        // 删除操作响应事件
        rowObj.getElementsByTagName('a')[2].onclick = function () {
            oTabNow.deleteRow(this.parentNode.parentNode.rowIndex);
            // 序号重新编号
            for(var i=1;i<oTabNow.rows.length;i++){oTabNow.rows[i].cells[0].innerHTML=i;}
        }
    }
    // 将存起来的内容复制到前一个表
    for(var i=1;i<rowNumsNow;i++){
        var rowObj = oTabBefore.insertRow(oTabBefore.rows.length); // 添加一行
        rowObj.insertCell(0).innerHTML = oTabBefore.rows.length-1;
        rowObj.insertCell(1).innerHTML = textArrayTemp[i-1];
        rowObj.insertCell(2).innerHTML = '<a>上移</a>';
        rowObj.insertCell(3).innerHTML = '<a>下移</a>';
        rowObj.insertCell(4).innerHTML = '<a>删除</a>';
        // 上移操作响应事件
        rowObj.getElementsByTagName('a')[0].onclick = function () {
            var tempIdx = this.parentNode.parentNode.rowIndex;
            if(tempIdx==1) {alert("已到顶端！");return;}
            var tempData = oTabBefore.rows[tempIdx].cells[1].innerHTML.toString();
            oTabBefore.rows[tempIdx].cells[1].innerHTML=oTabBefore.rows[tempIdx-1].cells[1].innerHTML.toString();
            oTabBefore.rows[tempIdx-1].cells[1].innerHTML=tempData;
        }
        // 下移操作响应事件
        rowObj.getElementsByTagName('a')[1].onclick = function () {
            var tempIdx = this.parentNode.parentNode.rowIndex;
            if(tempIdx==(oTabBefore.rows.length-1)) {alert("已到底部！");return;}
            var tempData = oTabBefore.rows[tempIdx].cells[1].innerHTML.toString();
            oTabBefore.rows[tempIdx].cells[1].innerHTML=oTabBefore.rows[tempIdx+1].cells[1].innerHTML.toString();
            oTabBefore.rows[tempIdx+1].cells[1].innerHTML=tempData;
        }
        // 删除操作响应事件
        rowObj.getElementsByTagName('a')[2].onclick = function () {
            oTabBefore.deleteRow(this.parentNode.parentNode.rowIndex);
            // 序号重新编号
            for(var i=1;i<oTabBefore.rows.length;i++){oTabBefore.rows[i].cells[0].innerHTML=i;}
        }

    }

};

// 删除数据的响应事件
function deleteMessage(type_num){
    var oTabNow = document.getElementById('tab_00'+ type_num.toString());
    var rowNumsNow = oTabNow.rows.length;
    for(var i=1;i<rowNumsNow;i++) {
        oTabNow.rows[1].getElementsByTagName('a')[2].onclick();
    }
}

// 删除所有的表格数据
function deleteAllMessage(){
    for(var i=0;i<tab_num_all;i++) {
        deleteMessage(i+1);
    }
}

// 将数组里面的数据加载到某表中
function addArrayToTab(type_num,data_array){
    // 将现在的表内容存储并清空
    var oTabNow = document.getElementById('tab_00'+ type_num.toString());
    // var rowNumsNow = oTabNow.rows.length;

    for(var i=0;i<data_array.length;i++) {
        var rowObj = oTabNow.insertRow(oTabNow.rows.length); // 添加一行
        rowObj.insertCell(0).innerHTML = oTabNow.rows.length-1;
        rowObj.insertCell(1).innerHTML = data_array[i];
        rowObj.insertCell(2).innerHTML = '<a>上移</a>';
        rowObj.insertCell(3).innerHTML = '<a>下移</a>';
        rowObj.insertCell(4).innerHTML = '<a>删除</a>';
        // 上移操作响应事件
        rowObj.getElementsByTagName('a')[0].onclick = function () {
            var tempIdx = this.parentNode.parentNode.rowIndex;
            if(tempIdx==1) {alert("已到顶端！");return;}
            var tempData = oTabNow.rows[tempIdx].cells[1].innerHTML.toString();
            oTabNow.rows[tempIdx].cells[1].innerHTML=oTabNow.rows[tempIdx-1].cells[1].innerHTML.toString();
            oTabNow.rows[tempIdx-1].cells[1].innerHTML=tempData;
        }
        // 下移操作响应事件
        rowObj.getElementsByTagName('a')[1].onclick = function () {
            var tempIdx = this.parentNode.parentNode.rowIndex;
            if(tempIdx==(oTabNow.rows.length-1)) {alert("已到底部！");return;}
            var tempData = oTabNow.rows[tempIdx].cells[1].innerHTML.toString();
            oTabNow.rows[tempIdx].cells[1].innerHTML=oTabNow.rows[tempIdx+1].cells[1].innerHTML.toString();
            oTabNow.rows[tempIdx+1].cells[1].innerHTML=tempData;
        }
        // 删除操作响应事件
        rowObj.getElementsByTagName('a')[2].onclick = function () {
            oTabNow.deleteRow(this.parentNode.parentNode.rowIndex);
            // 序号重新编号
            for(var i=1;i<oTabNow.rows.length;i++){oTabNow.rows[i].cells[0].innerHTML=i;}
        }
    }
}

// 根据数据类型编号，将某个数据类型移动到某个位置，同时表的名字改变
function adjustNumToindex(num_in,indx) {
    for(var j=0;j<reflect_table.length;j++)
    {
        // 找该数据类型的位置
        if(reflect_table[j].num==num_in){
            // 位置不一样的时候交换位置
            if(indx!=j)
            {
                var tempArray = reflect_table[j];
                reflect_table[j] = reflect_table[indx];
                reflect_table[indx] = tempArray;
                document.getElementById("type_00" + (indx+1).toString()).innerText = reflect_table[indx].type;
                document.getElementById("type_00" + (j+1).toString()).innerText = reflect_table[j].type;
            }
            break;
        }
    }
}

// 生成num数量的通道数组，用于初始化电类温度，FBG和环境温度
function genChannelArray(num) {
    var channelArray = new Array();
    channelArray.push({value:-1, num:"全选/反选", text:"全选/反选"});
    for(var i=0;i<num;i++) {
        channelArray.push({value:i+1, num:i+1, text:("第"+(i+1)+"通道")});
    }
    return channelArray;
}

// 生成num数量的节点数组，用于初始化电类温度，FBG和环境温度
function genMonitorArray(num) {
    var monitorArray = new Array();
    monitorArray.push({value:-1, num:"全选/反选", text:"全选/反选"});
    for(var i=0;i<num;i++) {
        monitorArray.push({value:i+1, num:i+1, text:("第"+(i+1)+"节点")});
    }
    return monitorArray;
}

// 可用于初始化电类，FBG，以及环境温度
function initComboBoxML(id,data_in){
    $(id).combobox({
        valueField: 'num',
        textField: 'text',
        panelHeight: 'auto',
        editable: false,
        data: data_in,
        multiple:true,
        onChange:function (newValue){
            var select = $(id);
            var valueField = select.combobox("options").valueField;
            if($.inArray("全选/反选", newValue)!=-1) {
                $('#channelId').attr('multiple',' true');
                if (!newValue[valueField]) {
                    var data = select.combobox("getData");
                    var values = select.combobox("getValues");
                    var selectVaues = [];
                    if (data.length!= values.length) {
                        data.reduce(function (prev, current, index, array) {
                            selectVaues.push(current[valueField]);
                        }, selectVaues);
                    } else {
                        selectVaues.push(newValue[valueField]);
                    }
                    selectVaues .splice(0,1);
                    select.combobox('setValues', selectVaues);
                }
            }
        }
    });
}

// 可用于初始化CCD
function initComboBoxCCD(){
    initComboBox('#dia-add #channelId',new Array({value:1, num:1, text:"CCD位移通道"}));
    initComboBoxML('#dia-add #monitorId',new Array(
        {value:-1, num:"全选/反选", text:"全选/反选"},
        {value:1, num:1, text:"X轴"},
        {value:2, num:2, text:"Y轴"},
        {value:3, num:3, text:"Z轴"}
        ));
}

// 可用于初始化CNC
function initComboBoxCNC(){
    initComboBox('#dia-add #channelId',new Array({value:1, num:1, text:"CNC机床数据"}));
    var cncDatArray = new Array({value:-1, num:"全选/反选", text:"全选/反选"});
    cncDatArray.push({value:'XPOS' , num:'XPOS' , text:"X轴坐标"});
    cncDatArray.push({value:'YPOS' , num:'YPOS' , text:"Y轴坐标"});
    cncDatArray.push({value:'ZPOS' , num:'ZPOS' , text:"Z轴坐标"});
    cncDatArray.push({value:'MAPOS', num:'MAPOS', text:"MA轴坐标"});
    cncDatArray.push({value:'XPWR' , num:'XPWR' , text:"X轴功率"});
    cncDatArray.push({value:'YPWR' , num:'YPWR' , text:"Y轴功率"});
    cncDatArray.push({value:'ZPWR' , num:'ZPWR' , text:"Z轴功率"});
    cncDatArray.push({value:'MAPWR', num:'MAPWR', text:"MA轴功率"});
    cncDatArray.push({value:'XFU'  , num:'XFU'  , text:"X轴负荷"});
    cncDatArray.push({value:'YFU'  , num:'YFU'  , text:"Y轴负荷"});
    cncDatArray.push({value:'ZFU'  , num:'ZFU'  , text:"Z轴负荷"});
    cncDatArray.push({value:'MAFU' , num:'MAFU' , text:"MA轴负荷"});
    cncDatArray.push({value:'FR'   , num:'FR'   , text:"进给速度"});
    cncDatArray.push({value:'SP'   , num:'SP'   , text:"主轴速度"});
    cncDatArray.push({value:'PA'   , num:'PA'   , text:"暂停状态"});
    // cncDatArray.push({value:'ERR'  , num:'ERR'  , text:"历史报警"});

    initComboBoxML('#dia-add #monitorId',cncDatArray);
}

// 对某个id的组合框用data_in数据初始化
function initComboBox(id,data_in) {                    // 加载设备缓存数组里面的设备
    $(id).combobox({
        valueField: 'num',
        textField: 'text',
        panelHeight: 'auto',
        editable: false,
        data: data_in
    });
}

// 从id中获取数据的类型
function getTypeFromID(type_id){
    var tcx= document.getElementById(type_id).innerText;
    tcx = tcx.split(' ');
    return(tcx[0]);
};

// 格式化日期函数
function formatOnlyDate(value){
    if(value==null){
        return null;
    }
    var date = new Date(value);
    var year = date.getFullYear().toString();
    var month = (date.getMonth() + 1);
    var day = date.getDate().toString();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    return year + "-" + month + "-" + day;
}
function formatOnlyTime(value){
    if(value==null){
        return null;
    }
    var date = new Date(value);
    var hour = date.getHours().toString();
    var minutes = date.getMinutes().toString();
    var seconds = date.getSeconds().toString();
    if (hour < 10) {
        hour = "0" + hour;
    }
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (seconds < 10) {
        seconds = "0" + seconds;
    }
    return hour + ":" + minutes + ":" + seconds;
}

// 生成下载连接函数
function genDownloadLink() {
    // 要下载的日期
    var tempStr = $('#machiningDate').combobox("getValues").toString().split('-');
    var machineDateStr = tempStr[0].substring(2,4)+tempStr[1]+tempStr[2];
    if(machineDateStr=="") {alert("加工日期不能为空！");return;}
    // 要下载的时间段
    var tempStr = $('#machiningProcess').combobox("getValues").toString().split('-');
    if(tempStr=="") {alert("加工时间段不能为空！");return;}
    var machineProcessStr = tempStr[0].split(':');
    // 要下载的起止时间
    var machineStartTimeStr = machineProcessStr[0]+machineProcessStr[1]+machineProcessStr[2];
    var machineProcessStr = tempStr[1].split(':');
    var machineEndTimeStr = machineProcessStr[0]+machineProcessStr[1]+machineProcessStr[2];

    // 下载目标字符串
    var stringArrayTemp=genAllDataString();
    if(stringArrayTemp=="") {alert("请添加传感器数据后再下载！");return;}
    window.top.showCFlowerMask();
    $.ajax({
        cache: false,
        url: "historysearch/combine2csvzero",			// 根据设备和工况类型以及日期来获取加工时间
        data: {date:machineDateStr,start:machineStartTimeStr,end:machineEndTimeStr,pattern:stringArrayTemp},
        type: "POST",
        dataType: "json",
        success: function (result) {
            window.top.hideCFlowerMask();
            if(result.success.toString()=="true"){
                console.log(result);
                var webLink = result.msg;
                var webFileName = result.msg.split("combine/")[1];
                downloadFile(webLink);
            }
            else {
                alert("生成数据文件失败！请稍候再试！")
            }
        },
        error: function(result){
            window.top.hideCFlowerMask();
             alert("生成数据文件失败！请稍候再试！");
        }
    });

    console.log(stringArrayTemp);
}

// 根据所有数据类型的表生成数据模式字符串
function genAllDataString() {
    var stringArrayTemp=new String();
    for(var i=0;i<5;i++){
        var oTabNow = document.getElementById('tab_00'+ (i+1).toString());
        var rowNumsNow = oTabNow.rows.length;
        if(rowNumsNow==1){continue;}
        // 获取列表内所有内容
        for(var j=1;j<rowNumsNow;j++){
            if(j==(rowNumsNow-1))   stringArrayTemp += oTabNow.rows[j].cells[1].innerHTML.toString()+'@';
            else                    stringArrayTemp += oTabNow.rows[j].cells[1].innerHTML.toString()+',';
        }
    }
    return stringArrayTemp;
}
// 生成下载连接函数
function downloadFile(url) {
    try {
        var elemIF = document.createElement("iframe");
        elemIF.src = url;
        elemIF.style.display = "none";
        document.body.appendChild(elemIF);
    } catch (e) {
    }
}
